package com.student.liu.controller;

import com.alibaba.fastjson.JSONObject;
import com.student.liu.service.IAdminService;
import com.student.liu.utils.TokenUtils;
import lombok.Data;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.xml.bind.ValidationException;
import java.util.Date;

/**
 * 用户类 控制器
 */
@RestController
public class AdminController extends BaseController {

    @Resource
    IAdminService adminService;

    /**
     * 用户登录
     * @param param
     * @return
     */
    @PostMapping("login")
    public Object login(@Valid @RequestBody LoginParam param, BindingResult result) throws ValidationException {
        //判断管理员账号和密码是否正常
        adminService.login(param.getUsername(), param.getPassword());

        Date issuedTime = new Date();
        Date expiresTime = new Date(issuedTime.getTime() + 1000 * 60 * 60 * 72);  //过期时间为72个小时
        JSONObject resultValue = new JSONObject();
        JSONObject sign = new JSONObject();
        sign.put("id", 1);
        sign.put("role", "admin");       //普通用户角色：user，管理员角色：admin
        resultValue.put("token", TokenUtils.generate(sign.toJSONString(), issuedTime, expiresTime));
        return success("登录成功", resultValue);
    }

    /**
     * 修改管理员密码
     * @param newPassword   新密码
     * @return
     */
    @PostMapping("changePassword")
    @PreAuthorize("hasRole('ROLE_admin')")
    public Object changePassword(@RequestParam String newPassword) {
        adminService.changePwd("admin", newPassword);
        return success("修改成功", null);
    }

    @Data
    static class LoginParam{
        @NotBlank(message = "用户名不能为空")
        private String username;
        @NotBlank(message = "密码不能为空")
        private String password;
    }


}
